package ${map.basePackage}.controller;


import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rulian.base.common.dto.Message;
import cn.rulian.base.common.vo.Result;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;

import ${curd.boPath};
import ${map.basePackage}.service.${map.boName}Service${temp};
import ${map.basePackage}.vo.${map.boName}Vo;

/**
 * ${curd.name} Controller
 */

@Controller
@RequestMapping("/${map.projectName}/${map.groupName}/${map.boName_low}")
public class ${map.boName}Controller${temp} {
	
	@Autowired
	private ${map.boName}Service${temp} service;
	
	private final String path="${map.projectName}/${map.groupName}/${map.boName_low}_"; //页面基本路径

	/**
	 * 页面基本路径
	 */
	private String getPath()
	{
		return path;
	}
	
	/**
	 * 列表页面
	 */
	@RequestMapping("/listPage")
	public String listPage() {
		return this.getPath()+"list";
	}

	/**
	 * 查询
	 */
	@RequestMapping("/listData")
	@ResponseBody
	public Result listData(${map.boName}Vo vo) {
		return service.query(vo);
	}

	/**
	 * 增加页面
	 */
	@RequestMapping("/addPage")
	public String addPage() {
		return this.getPath()+"add";
	}

	/**
	 * 增加
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Message add(${map.boName}Vo vo, HttpSession session) {
	
		//User user = UserInfo.getUserInfo(session).getUser();
		
		Message rm = new Message();
		${map.boName} bo = vo.getObj();
		try {
			
			service.save(bo);
			
			rm.setMsg("保存成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("保存失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 修改页面
	 */
	@RequestMapping("/updatePage")
	public String updatePage(Model model, Long id) {
		model.addAttribute("bo", service.findOne(id));
		return this.getPath()+"update";
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Message update(${map.boName}Vo vo,Long id) {
		Message rm = new Message();
		try {
			${map.boName} obj = vo.getObj();
			${map.boName} bo = service.findOne(id);
			
		<#list updateFields as item>
			bo.set${item.fieldName?cap_first}(obj.get${item.fieldName?cap_first}());
    	</#list>
			service.save(bo);
			
			rm.setMsg("保存成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("保存失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Message delete(Long ids[]) {
		Message rm = new Message();
		try {
			for(Long id:ids)
			{
				service.delete(id);
			}
			
			rm.setMsg("删除成功！");
			rm.setCode(Message._SUCCESS);
		} catch (Exception e) {
			rm.setMsg("删除失败，异常信息：<br/>" + e.toString());
			rm.setCode(Message._ERROR);
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 详情页面
	 */
	@RequestMapping("/detailPage")
	public String detailPage(Model model, Long id) {
		model.addAttribute("bo", service.findOne(id));
		return this.getPath()+"detail";
	}
	
	/**
	 * 导出Excel
	 * @throws Exception 
	 */
	@RequestMapping("/exportExcel")
	public void exportExcel(HttpServletResponse response, ${map.boName}Vo vo) throws Exception {
		
		String bookName = "${curd.name}"; //文件名
		
		File file = File.createTempFile("Export", "xls"); //创建临时文件
		jxl.write.WritableWorkbook book = Workbook.createWorkbook(file); //工作薄
		jxl.write.WritableSheet sheet = book.createSheet("Sheet1", 0); //工作表
		
		//通用设置
		sheet.getSettings().setDefaultRowHeight(400); //空白行高度
		sheet.getSettings().setDefaultColumnWidth(12); //默认列宽
		sheet.setColumnView(0, 8);//第1列 宽度（序号）
		
		//输出标题
		{
			String title = "${curd.name}"; //标题
			
			<#assign k=0 />
			<#list listFields as item>
				<#assign k=k+1 />
    		</#list>
    		
			int lieNum = ${k}; //总列数（标题跨列用）
			
			//标题行高
			sheet.setRowView(0, 700); //第1行
			
			//标题样式
			WritableCellFormat formatterTitle= new WritableCellFormat(); 
			formatterTitle.setAlignment(Alignment.CENTRE);//水平对齐
			formatterTitle.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直对齐
			WritableFont font = new WritableFont(WritableFont.TAHOMA, 18, WritableFont.BOLD, false); //字体
			formatterTitle.setFont(font);

			//输出标题
			sheet.mergeCells(0, 0, lieNum, 0); //合并单元格
			sheet.addCell(creatLabel(0,0,formatterTitle,title)); //输出标题
		}
		
		//行列号
		int rowNum = 1; //行号
		int columnNum = 0; //列号

		//输出列标题
		{
			//列标题 行高
			sheet.setRowView(1, 500);//第2行
			
			//列标题样式
			WritableCellFormat formatterColumnTitle= new WritableCellFormat(); //列标题样式
			formatterColumnTitle.setAlignment(Alignment.CENTRE);//水平对齐
			formatterColumnTitle.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直对齐
			formatterColumnTitle .setBackground(Colour.GRAY_25);//背景色
			formatterColumnTitle.setBorder(Border.ALL, BorderLineStyle.THIN);//边框线  所有边框 细线
			
			//列标题
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "序号"));
		<#list listFields as item>
			sheet.addCell(creatLabel(rowNum,columnNum++,formatterColumnTitle, "${item.showName!item.fieldName}"));
    	</#list>
			
		}
		
		//输出内容
		List<${map.boName}> list = service.QueryExcelData(vo); //输出数据
		if(list != null && list.size() > 0)
		{
			SimpleDateFormat formatterDate = new SimpleDateFormat("yyyy-MM-dd"); //日期格式化
			SimpleDateFormat formatterDate2 = new SimpleDateFormat("yyyy-MM"); //年月格式化
			SimpleDateFormat formatterTime = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //时间格式化
			
			//内容样式
			WritableCellFormat formatterCon= new WritableCellFormat(); //内容样式
			formatterCon.setAlignment(Alignment.CENTRE);//水平对齐
			formatterCon.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直对齐
			formatterCon.setBorder(Border.ALL, BorderLineStyle.THIN);//边框线  所有边框 细线
			
			//定义变量
			<#list listFields as item>
			String ${item.fieldName}Str = ""; // ${item.showName!item.fieldName}
    		</#list>
			
			for(int i = 0; i < list.size(); i++)
	    	{
				rowNum++;
				columnNum=0;

				sheet.setRowView(rowNum, 400); //行高
				
				//初始化变量
			<#list listFields as item>
				${item.fieldName}Str = ""; // ${item.showName!item.fieldName}
    		</#list>
				
				//变量赋值
				${map.boName} bo = list.get(i); 
			<#list listFields as item>
				<#if item.fieldType == "java.lang.Boolean">
					<#-- 02 开关  -->
					<#if item.addType == "B02">
				if(bo.get${item.fieldName?cap_first}()!= null){	${item.fieldName}Str = bo.get${item.fieldName?cap_first}()?"是":"否";	} //${item.showName!item.fieldName}
	           		<#-- 是否  -->
	           		<#else>
				if(bo.get${item.fieldName?cap_first}() != null){	${item.fieldName}Str = bo.get${item.fieldName?cap_first}()?"开":"关";		} //${item.showName!item.fieldName}
	           		</#if>
	           	<#elseif item.fieldType == "java.util.Date">
		           	<#--  时间  -->
	           		<#if (item.addType == "DT03" || item.addType == "DT04")>
				if(bo.get${item.fieldName?cap_first}() != null){	${item.fieldName}Str = formatterTime.format(bo.get${item.fieldName?cap_first}());	} //${item.showName!item.fieldName}
	           		<#--  年月  -->
	           		<#elseif (item.addType == "DT05")>
				if(bo.get${item.fieldName?cap_first}() != null){	${item.fieldName}Str = formatterDate2.format(bo.get${item.fieldName?cap_first}());	} //${item.showName!item.fieldName}
	           		<#--  日期 -->
	           		<#else>
				if(bo.get${item.fieldName?cap_first}() != null){	${item.fieldName}Str = formatterDate.format(bo.get${item.fieldName?cap_first}());	} //${item.showName!item.fieldName}
	           		</#if>
				<#elseif item.otherBo>
				if(bo.get${item.fieldName?cap_first}() != null){	${item.fieldName}Str = bo.get${item.fieldName?cap_first}().get${item.urlShowField?cap_first}();	} //${item.showName!item.fieldName}
	           	<#else>
				if(bo.get${item.fieldName?cap_first}() != null){	${item.fieldName}Str = bo.get${item.fieldName?cap_first}().toString();	} //${item.showName!item.fieldName}
	           	</#if>
    		</#list>
		
								
				//输出一行数据
	    		sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, (i+1)+"")); 
	    	<#list listFields as item>
			    sheet.addCell(creatLabel(rowNum,columnNum++,formatterCon, ${item.fieldName}Str)); // ${item.showName!item.fieldName}
    		</#list>	
	    		
	    	}
		}

		book.write();
		book.close();
		
		//-------------------------------

		FileInputStream f = new FileInputStream(file);
		byte[] fb = new byte[f.available()];
		f.read(fb);
		response.setHeader("Content-disposition", "attachment; filename=" + new String((bookName + ".xls").getBytes("gb2312"), "iso8859-1"));
		ByteArrayInputStream bais = new ByteArrayInputStream(fb);
		int b;
		while ((b = bais.read()) != -1)
		{
			response.getOutputStream().write(b);
		}
		response.getOutputStream().flush();
		f.close();
	}
	
	private Label creatLabel(int rowNum, int columnNum, WritableCellFormat formatter, String con) //行，列，样式，内容 
	{  
		 return new Label(columnNum, rowNum, con,formatter);   
	}  
}
